package service;

import dao.UserDao;
import donain.User;
import exception.ActiveUserException;
import exception.LoginException;
import utilts.MailUtils;
import utilts.Response;
import utilts.ResponseCode;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import java.sql.SQLException;
import java.util.Date;


public class UserService {
    UserDao userDao=new UserDao();


    public void active(String activeCode) throws ActiveUserException {
        Response bulid=null;
        try {
            User user=  userDao.findUserByActiveCode(activeCode);
            if(user==null){
                throw new ActiveUserException(ResponseCode.ERROR_ACTIVE);
            }
            Date registTime=   user.getRegistTime();
            Long currentTime=System.currentTimeMillis();
            Long time=currentTime-registTime.getTime();
            if (time/1000/60/60>24){
                throw new ActiveUserException(ResponseCode.EEROR_ExPIRE);
            }
            userDao.activeUser(activeCode);
        }catch (SQLException e){
            e.printStackTrace();
//            Response bulid=Response.build(ResponseCode.ERROR_DB);
            throw  new ActiveUserException(ResponseCode.ERROR_DB);
        }

    }


    public boolean register(User user)  {
        try {
            userDao.addUser(user);
            String emailMsg = "感谢您注册网上书城，点击"
                    + "<a href='http://localhost:8080/bookstore/activeUser?activeCode="
                    + user.getActiveCode() + "'>&nbsp;激活&nbsp;</a>后使用。"
                    + "<br />为保障您的账户安全，请在24小时内完成激活操作";
            MailUtils.sendMail(user.getEmail(), emailMsg);
                return true;
        }
        catch (Exception e){
            e.printStackTrace();
            return false;
    }
    }


    public  User login(User user)throws LoginException{

       User useDB= null;
       try {
            useDB= userDao.findUserByUsernameAndPassword(user.getUsername(),user.getPassword());
       }catch (SQLException e){
           e.printStackTrace();
           throw  new LoginException(ResponseCode.ERROR_DB);

       }
       if(useDB!=null){
           if(useDB.getState()==1){
               System.out.println(user.getRole());
               return  useDB;
           }
           else {

               throw  new LoginException(ResponseCode.NOT_ACTIVE);
           }
       }
       else {
           throw  new LoginException(ResponseCode.ERROR_NAME_PASSWORD);
       }
    }
}


